package me.pinion.oss;

import java.io.*;
import java.net.URL;
import java.util.*;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.*;
import me.pinion.Log;

public class BucketKit {

    public static String ACCESS_KEY_ID = "wEPUTuBZBBar8Fgq";
    public static String ACCESS_KEY_SECRET = "zTPUTyUExvxEABh2Ln94ZIYkw80CZL";
    public static String BUCKET_NAME = "xtime";
    public static int EXPIRATION = 3600 * 1000;

    private static OSSClient CLIENT = new OSSClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);


    /**
     *
     * @param file
     * @return key
     * @throws FileNotFoundException
     */
    public static String upload(File file) throws FileNotFoundException{
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        String filename = file.getName();
        String key = year + "/"
                + (month > 9 ? month : "0" + month) + (date > 9 ? date : "0" + date) + "/"
                + new Date().getTime() + "." + filename.substring(filename.lastIndexOf('.') + 1);
        return upload(file, key);
    }

    /**
     *
     * @param file
     * @return key
     * @throws FileNotFoundException
     */
    public static String upload(File file, String key) throws FileNotFoundException{
        Long start = System.currentTimeMillis();
        Log.i("start ::: " + start);
        InputStream content = new FileInputStream(file);
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.length());
        BucketKit.CLIENT.putObject(BucketKit.BUCKET_NAME, key, content, meta);
        Long stop = System.currentTimeMillis();
        Log.i("stop ::: " + stop);
        Log.i("total ::: " + (stop - start));
        return key;
    }

    /**
     *
     * @param key
     * @return URL
     */
    public static String getURL(String key){
        URL url = CLIENT.generatePresignedUrl(BUCKET_NAME, key, new Date(new Date().getTime() + EXPIRATION));
        return url.getProtocol() + "://" + url.getHost() + url.getFile();
    }
}